<template>
  <div>
    <div  class="uploader" v-if="actionType == 'CreateUploadVideo'">
      <input type="file" :id="id" style="display: none;" @change="fileChange($event)">
      <label :for="id" class="status">{{messageTxt}}</label>
    </div>

    <div  class="img_uploader" v-if="actionType == 'CreateUploadImage'">
      <input type="file" :id="id" style="display: none;" @change="fileChange($event)">
      <img v-if="imgUrl" :src="imgUrl" class="image" alt="" @click="clickUpdate(id)">
      <label :for="id" class="label"></label>
    </div>
  </div>
</template>

<style scoped>
.img_uploader {
  display: inline-block;
  width: 80px;
  height: 80px;
  border: 1px dashed #77A4FF;
  border-radius: 5px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.image{
  display: inline-block;
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 99999;
}
.label {
  display: inline-block;
  width: 100%;
  height: 100%;
  cursor: pointer;
}
.uploader {
  width: 100%;
  height: 100%;
}
.label:after{
  content: '+';
  display: inline-block;
  font-size: 35px;
  color: #77A4FF;
  font-weight: 100;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.status {
  font-size: 12px;
  color: #77A4FF;
  cursor: pointer;
}
</style>
<script>
import axios from 'axios'
import {
  createNamespacedHelpers,
  mapState
} from "vuex";
let {
  mapGetters,
  mapActions
} = createNamespacedHelpers("adminBasic");

export default {
  data() {
    return {
      id: Number(Math.random().toString().substr(3, 16) + Date.now()).toString(36),

      timeout: '',
      partSize: '',
      parallel: '',
      retryCount: '',
      retryDuration: '',
      region: 'cn-shanghai',
      userId: '1303984639806000',
      file: null,
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: '',
      Signature: '',
      Timestamp: '',
      SignatureNonce: '',

      uploadData: {},
    }
  },

  created() {
    
  },

  methods: {
    ...mapActions([
      "formGet",
      "post"
    ]),
    clickUpdate(id) {
      document.getElementById(id).click();
    },
    getSignature() {
      console.log(this.actionType)
      let data
      if(this.actionType == 'CreateUploadVideo') {
        data = {
          Action: this.actionType,
          Title: this.file.name,
          FileName: this.file.name,
          FileSize: this.file.size,
          TerminalType: 'pc',
          Format: 'JSON',
        }
      }else if (this.actionType == 'CreateUploadImage') {
        data = {
          Action: this.actionType,
          ImageType: 'default',
          TerminalType: 'pc',
          Format: 'JSON',
        }
      }
      this.post({
        API: 'getSignature',
        data: data
      }).then(res => {
        console.log(res);
        this.Signature = res.Signature;
        this.Timestamp = res.Timestamp;
        this.SignatureNonce = res.SignatureNonce;

        this.uploader.startUpload()
      })
    },
    fileChange (e) {
      this.file = e.target.files[0]
      if (!this.file) {
        alert("请先选择需要上传的文件!")
        return
      }
      this.getSignature();
      var Title = this.file.name
      var userData = '{"Vod":{}}'
      if (this.uploader) {
        this.uploader.stopUpload()
        this.authProgress = 0
        this.statusText = ""
      }
      this.uploader = this.createUploader()
      console.log(userData)
      this.uploader.addFile(this.file, null, null, null, userData)
      this.uploadDisabled = false
      this.pauseDisabled = true
      this.resumeDisabled = true

      // this.uploader.startUpload()
    },
    authUpload () {
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload()
        this.uploadDisabled = true
        this.pauseDisabled = false
      }
    },
    // 暂停上传
    pauseUpload () {
      if (this.uploader !== null) {
        this.uploader.stopUpload()
        this.resumeDisabled = false
        this.pauseDisabled = true
      }
    },
    // 恢复上传
    resumeUpload () {
      if (this.uploader !== null) {
        this.uploader.startUpload()
        this.resumeDisabled = true
        this.pauseDisabled = false
      }
    },
    createUploader (type) {
      let self = this
      let uploader = new AliyunUpload.Vod({
        timeout: self.timeout || 60000,
        partSize: self.partSize || 1048576,
        parallel: self.parallel || 5,
        retryCount: self.retryCount || 3,
        retryDuration: self.retryDuration || 2,
        region: self.region,
        userId: self.userId,
        // 添加文件成功
        addFileSuccess: function (uploadInfo) {
          self.uploadDisabled = false
          self.resumeDisabled = false
          self.statusText = '添加文件成功, 等待上传...'
          console.log("addFileSuccess: " + uploadInfo.file.name)
          console.log(uploadInfo);
        },
        // 开始上传
        onUploadstarted: function (uploadInfo) {
          // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
          // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
          // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
          // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
          // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
          // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
          if (!uploadInfo.videoId) {
            let createUrl
            if(self.actionType == 'CreateUploadVideo') {
              createUrl = `http://vod.cn-shanghai.aliyuncs.com/?Action=CreateUploadVideo&Version=2017-03-21&Signature=${self.Signature}&SignatureMethod=HMAC-SHA1&SignatureNonce=${self.SignatureNonce}&SignatureVersion=1.0&AccessKeyId=LTAInJTcaT8cj76F&Timestamp=${self.Timestamp}&Title=${uploadInfo.file.name}&FileName=${uploadInfo.file.name}&FileSize=${uploadInfo.file.size}&TerminalType=pc&Format=JSON`
            }else if (self.actionType == 'CreateUploadImage') {
              createUrl = `http://vod.cn-shanghai.aliyuncs.com/?Action=CreateUploadImage&ImageType=default&Version=2017-03-21&Signature=${self.Signature}&SignatureMethod=HMAC-SHA1&SignatureNonce=${self.SignatureNonce}&SignatureVersion=1.0&AccessKeyId=LTAInJTcaT8cj76F&Timestamp=${self.Timestamp}&TerminalType=pc&Format=JSON`
            }
            axios.get(createUrl).then(({data}) => {
              // console.log(data);
              let uploadAuth = data.UploadAuth
              let uploadAddress = data.UploadAddress
              let videoId = data.VideoId
              data.fileName = self.file.name
              self.uploadData = data
              uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)                
            })
            self.statusText = '文件开始上传...'
            console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
          } else {
            // 如果videoId有值，根据videoId刷新上传凭证
            // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
            let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
            axios.get(refreshUrl).then(({data}) => {
              let uploadAuth = data.UploadAuth
              let uploadAddress = data.UploadAddress
              let videoId = data.VideoId
              uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
            })
          }
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
          console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
          self.statusText = '文件上传成功!'
          
          
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
          console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
          self.statusText = '文件上传失败!'
        },
        // 取消文件上传
        onUploadCanceled: function (uploadInfo, code, message) {
          console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
          self.statusText = '文件已暂停上传'
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function (uploadInfo, totalSize, progress) {
          console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
          let progressPercent = Math.ceil(progress * 100)
          self.authProgress = progressPercent
          self.statusText = '文件上传中...'
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
          axios.get(refreshUrl).then(({data}) => {
            let uploadAuth = data.UploadAuth
            uploader.resumeUploadWithAuth(uploadAuth)
            console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
          })
          self.statusText = '文件超时...'
        },
        // 全部文件上传结束
        onUploadEnd: function (uploadInfo) {
          console.log("onUploadEnd: uploaded all the files")
          self.statusText = '文件上传完毕'

          self.$emit('uploadSuccess', self.uploadData);
        }
      })
      return uploader
    }
  },

  props: ['messageTxt', 'actionType', 'imgUrl']
}
</script>


<style scoped>
  
</style>